﻿using System.IO;
using System.Reflection;
using System.Xml;
using System.Xml.Schema;

namespace CodeContrib
{
	public static class XmlSchemaExtensions
	{
		public static XmlSchema GetEmbeddedSchema(this Assembly assembly, string schemaName)
		{
			Guard.NotNull(assembly, "assembly");

			var schemaPath = string.Format("{0}.{1}", assembly.GetName().Name, schemaName);

			var stream = assembly.GetManifestResourceStream(schemaPath);

			if (stream == null)
			{
				throw new FileNotFoundException();
			}

			return XmlSchema.Read(stream, ValidationEventHandler);
		}

		public static void ValidateSchema(this string xml, XmlSchemaSet schemas)
		{
			var settings = new XmlReaderSettings
				               {
					               IgnoreWhitespace = true,
					               ValidationType = ValidationType.Schema,
					               ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings,
				               };

			settings.Schemas.Add(schemas);
			settings.ValidationEventHandler += ValidationEventHandler;

			var reader = XmlReader.Create(new StringReader(xml), settings);

			while (reader.Read())
			{
			}
		}

		private static void ValidationEventHandler(object sender, ValidationEventArgs e)
		{
			throw e.Exception;
		}
	}
}